//
//  SDetileViewController.m
//  Gegeda_music_MY
//
//  Created by lanou3g on 15/11/2.
//  Copyright © 2015年 周莹. All rights reserved.
//
#import "SearchViewController.h"
#import "SDetileViewController.h"
#import "Colours.h"
#import "UIView+Extension.h"
#import "textviewMusic.h"
#import "HMComposePhotosView.h"
#import "HMComposeToolbar.h"
#import "AFNetworking.h"
#import "HMAccount.h"
#import "HMAccountTool.h"
#import "MBProgressHUD+MJ.h"
#define Heght      [UIScreen  mainScreen].bounds.size.height-60

@interface SDetileViewController()<ComposeToolbardelegate,UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property(nonatomic,weak)textviewMusic  *textView;
@property(nonatomic,weak)HMComposeToolbar *toolbar;
@property(nonatomic,weak)HMComposePhotosView *photosView;

@end

@implementation SDetileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置导航条内容
    [self  setupNavBar];
    
    //添加输入控件
    [self  setuptextView];
    
    //添加工具条
    [self  setupToolBar];
    
    //添加显示图片的相册控件
    
    [self  setupPhotosView];
    

  
}
//添加显示是图片的相册控件
-(void)setupPhotosView{

    HMComposePhotosView  *potosview= [[HMComposePhotosView  alloc] init];
    potosview.width = self.textView.width;
    potosview.height = self.textView.height;
    potosview.y = 70;
    [self  .textView  addSubview:potosview];
    self.photosView = potosview;





}

//添加工具条
-(void)setupToolBar{

//1:创建
    HMComposeToolbar  *toolbar = [[HMComposeToolbar  alloc] init];
    toolbar.width = self.view.width;
    toolbar.delegate = self;
    toolbar.height = 44;
    self.toolbar = toolbar;

//2:显示
    toolbar.y = self.view.height -self.textView.height+200;
    [self  .view  addSubview:toolbar];




}

//添加输入控件
-(void)setuptextView{

//1:创建输入控件
    textviewMusic *textView = [[textviewMusic  alloc] init];
    //垂直方向拥有弹簧效果
    textView .alwaysBounceVertical = YES;
    textView.frame = self.view.bounds;
    textView.delegate = self;
    [self .view  addSubview:textView];
    self.textView = textView;
    //设置提醒文字
    textView.placehoder = @"分享新鲜事";
    //设置字体
    textView.font = [UIFont  systemFontOfSize:15];
    // 4.监听键盘
    // 键盘的frame(位置)即将改变, 就会发出UIKeyboardWillChangeFrameNotification
    // 键盘即将弹出, 就会发出UIKeyboardWillShowNotification
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShou:) name:UIKeyboardWillShowNotification object:nil];
    // 键盘即将隐藏, 就会发出UIKeyboardWillHideNotification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    


}

-(void)dealloc{

    [[NSNotificationCenter  defaultCenter] removeObserver:self];

}

// view显示完毕的时候再弹出键盘，避免显示控制器view的时候会卡住

-(void)viewDidAppear:(BOOL)animated{

    [super  viewDidAppear:animated];
    //成为第一响应者(呼出键盘)
    [self.textView becomeFirstResponder];

}


//设置导航栏内容
-(void)setupNavBar{
self.title = @"发消息";
    self.view.backgroundColor = [UIColor  pinkLipstickColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem  alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(send)];

    self.navigationItem.rightBarButtonItem.enabled = YES;

    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backDidClicked)];
    
    self.navigationItem.rightBarButtonItem.enabled = YES;

}

-(void)backDidClicked{

    [self.navigationController  popToViewController:[self.navigationController.viewControllers  objectAtIndex:1] animated:YES];



}



//取消
-(void)cancel{

    [self  dismissViewControllerAnimated:YES completion:nil];



}

-(void)send{

//发消息
    if (self.photosView.image.count) {
        [self  sendStatusWithImage];
    }else{
    
        [self  sendStautesWithoutImage];
    
    }
//2:关闭控制器
    [self  dismissViewControllerAnimated:YES completion:nil];

}

//发表有图片的消息
-(void)sendStatusWithImage{
//获取请求管理者
    AFHTTPRequestOperationManager  *mar = [AFHTTPRequestOperationManager  manager];
    //2:封装请求参数
    NSMutableDictionary  *params = [NSMutableDictionary dictionary ];
    
    params[@"access_token"] = [HMAccountTool account].access_token;
    
    params[@"status"] = self.textView.text;
    
    // 3.发送POST请求
    [mar POST:@"https://upload.api.weibo.com/2/statuses/upload.json" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
#warning 目前新浪开放的发微博接口 最多 只能上传一张图片
        UIImage *image =[self .photosView.image  firstObject];
        NSData *data = UIImageJPEGRepresentation(image, 1.0);
        
        // 拼接文件参数
        [formData appendPartWithFileData:data name:@"pic" fileName:@"status.jpg" mimeType:@"image/jpeg"];
        
    } success:^(AFHTTPRequestOperation *operation, NSDictionary *statusDict) {
        [MBProgressHUD showSuccess:@"发表成功"];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD showError:@"发表失败"];
    }];
    
  
}

// 图文混排 ： 图片和文字混合在一起排列
//发表没有图片的微博

//1:获得请求管理者
-(void)sendStautesWithoutImage{
    AFHTTPRequestOperationManager  *mar = [AFHTTPRequestOperationManager manager];
    
    //2:封装请求参数
    NSMutableDictionary  *params = [NSMutableDictionary  dictionary ];
    
    
    params[@"access_token"] = [HMAccountTool  account].access_token;
    params[@"status"] = self.textView.text;
    
    //3:发送post请求
    [mar  POST:@"https://api.weibo.com/2/statuses/update.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [MBProgressHUD  showSuccess:@"发表成功"];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [MBProgressHUD  showError:@"发表失败"];
    }];
    
    
}

//键盘即将弹出
-(void)keyboardWillShou:(NSNotification  *)note{
//1:键盘弹出的需要时间
    CGFloat  duration = [note.userInfo [UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    
    //2动画
    [UIView  animateWithDuration:duration animations:^{
        //1:取出键盘的高度
        //用户结束编辑的键盘
        CGRect  keboardF = [note  .userInfo  [UIKeyboardFrameEndUserInfoKey]CGRectValue];
        CGFloat keboarH = keboardF.size.height;
        
        self.toolbar.transform = CGAffineTransformMakeTranslation(0, -keboarH);
        
    }];
    
    
}



/**
 *  键盘即将隐藏
 */
- (void)keyboardWillHide:(NSNotification *)note
{
    // 1.键盘弹出需要的时间
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 2.动画
    [UIView animateWithDuration:duration animations:^{
        self.toolbar.transform = CGAffineTransformIdentity;
    }];
}

#pragma mark UitextViewDelegate

//当用户开始拖拽scrollView时调用
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view  endEditing:YES];


}

//当textView的文字改变就会调用

-(void)textViewDidChange:(UITextView *)textView{

    self.navigationItem.rightBarButtonItem.enabled = textView.text.length!=0;


}

#pragma mark - HMComposeToolbarDelegate
//监听toobar 内部按钮的点击
-(void)composeTool:(HMComposeToolbar *)tobar didClickedButton:(ComposeToolbarButtonType)buttonType{


    switch (buttonType) {
        case ComposeToolbarButtonTypeCamera:
            [self  openCamera];
            break;
        case ComposeToolbarButtonTypePicture:
            [self  openAlBum];
            break;
        case ComposeToolbarButtonTypeEmotion:
            [self  openEmotion];
            break;
        default:
            break;
    }



}

// 打开照相机
-(void)openCamera{
    if (![UIImagePickerController  isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        return;
        
        UIImagePickerController  *ipc = [[UIImagePickerController  alloc] init];
        ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
        ipc.delegate = self;
        [self  presentViewController:ipc animated:YES completion:nil];
        
        
    }



}

//打开相机
-(void)openAlBum{

    if (![UIImagePickerController  isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        return;
        
    }

    
    UIImagePickerController   *ips  = [[UIImagePickerController  alloc] init];
    ips.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    
    ips.delegate = self;
    [self  presentViewController:ips animated:YES completion:nil];
    

}


//打开表情

-(void)openEmotion{





}

#pragma maek _UImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker  dismissViewControllerAnimated:YES completion:nil];
    
    
    //1:取出图片
    UIImage  *image = info[UIImagePickerControllerOriginalImage];
    //2:添加图片到相册i
    [self.photosView  addImage:image];
    





}




@end
